<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends HYD_Controller {
    private $_search_field_arr  = array();
    private $_add_field_arr = array();
    private $_edit_field_arr = array();
    private $_save_field_valid_arr = array(); //验证部分字段提交过来的值是否在有效范围内 
    
    public function __construct(){
        parent::__construct();
        $this->load->model('user/user_model');
        $this->field_lists_init();
    }
    
    private function field_lists_init(){  
        //搜索中的“查询条件”选单                 
        $this->_search_field_arr = array('name'=> '姓名',
                                         'tel'=> '手机号');
        //添加action的数组
        $this->_add_field_arr = array('provinceid', 'cityid', 'teamid', 'departmentid', 'positionid',
            'name', 'sex', 'username', 'tel', 'worknum','entrytime');
        //修改action的数组
        $this->_edit_field_arr = array('id','provinceid', 'cityid', 'teamid', 'departmentid', 'positionid',
            'name', 'sex', 'username', 'tel', 'worknum','entrytime');

        //生成规则
        $field_lists = array(); //text/dropdown/dropdownedit/checkbox/radio/date/time/datetime    
        $field_lists['id'] = array('rules' => 'required', 'ftype' => '', 'datasource' => '', 'default' => '', 'label' => '');
        $field_lists['provinceid'] = array('rules' => 'required', 'ftype' => 'dropdown', 'datasource' => 'get_organize_list', 'default' => '', 'label' => '');
        $field_lists['cityid'] = array('rules' => 'required', 'ftype' => 'dropdown', 'datasource' => 'get_group_list', 'default' => '', 'label' => '');
        $field_lists['teamid'] = array('rules' => '', 'ftype' => 'dropdown', 'datasource' => 'get_department_tree', 'default' => '', 'label' => '');
        $field_lists['departmentid'] = array('rules' => 'required', 'ftype' => 'text', 'datasource' => '', 'default' => '', 'label' => '');
        $field_lists['positionid'] = array('rules' => '', 'ftype' => 'text', 'datasource' => '', 'default' => '', 'label' => '');
        $field_lists['name'] = array('rules' => '', 'ftype' => 'text', 'datasource' => '', 'default' => '', 'label' => '');
        $field_lists['sex'] = array('rules' => '','ftype' => 'checkbox', 'datasource' => array('F' => '女', 'M' => '男'), 'default' => '女', 'checked' => TRUE, 'label' => '');
        $field_lists['level'] = array('rules' => '','ftype' => 'checkbox', 'datasource' => array(0 => '员工', 1 => '主管', 2=> '总经理'), 'default' => '女', 'checked' => TRUE, 'label' => '');
        $field_lists['username'] = array('rules' => '', 'ftype' => 'text', 'datasource' => '', 'default' => '', 'label' => '');
        $field_lists['tel'] = array('rules' => '', 'ftype' => 'text', 'datasource' => '', 'default' => '', 'label' => '');
        $field_lists['worknum'] = array('rules' => '', 'ftype' => 'text', 'datasource' => '', 'default' => '', 'label' => '工号');
        $field_lists['entrytime'] = array('rules' => '', 'ftype' => 'date', 'datasource' => '', 'default' => '', 'label' => '入职时间');
        //设置label
        foreach ($field_lists as $field => $field_arr) {
            if (isset($field_arr['checked'])) {
                $this->_save_field_valid_arr[] = $field;
            }
        }
        $this->set_field_lists($field_lists);
    }
    
    public function list_user(){
        //$module = $this->input->get('module');
        //$action = $this->input->get('action');
        //log_message('error', $module.'-'.$action.'-begin index-'.microtime());
        $sql_str = '';
        $start = $this->input->get_post('start') ? $this->input->get_post('start') : 0;
        $limit = $this->input->get_post('limit') ? $this->input->get_post('limit') : MAX_DISPLAY_SEARCH_RESULTS;
        $search_type = $this->input->get_post('search_type');
        if($search_type == 'button'){
            $search_content = $this->input->get_post('search_content');
            $sql_str .= 'classid='.$search_content;
        }elseif($search_type == 'text'){
            $search_content = $this->input->get_post('search_content');
            if (strlen(trim($search_content)) > 0) {
                $value = addslashes($search_content);
                $search_field_arr = array_keys($this->_search_field_arr);
                foreach ($search_field_arr as $field) {
                    if ($sql_str){
                        $sql_str .= ' OR ';
                    }
                    $sql_str .= "{$field} like '%{$value}%'";
                }
            }
        }
        
        $user = $this->user_model->get_lists($start, $limit, $sql_str);  

        $this->load->model('department/department_model');
        $this->load->model('team/team_model');
        //将部门、团队名称转为真正名称      
        foreach ($user as $k => $v) {
            $department_arr = $this->department_model->get_data($v['departmentid']);
            $team_arr = $this->team_model->get_data($v['teamid']);
            
            $user[$k]['department_name'] = $department_arr['name'];
            $user[$k]['team_name'] = $team_arr['name'];
        }
        
        $response = array(EXT_JSON_READER_TOTAL => $this->user_model->get_total(),
                          EXT_JSON_READER_ROOT => $user);
        
        $this->output->set_content_type('application/json')->set_output(json_encode($response));
        //return $response;
    }
    
    /**
     * 添加用户/员工
     */
    public function add_user() {
        foreach ($this->get_field_lists() as $field => $rules) {
            if (in_array($field, $this->_add_field_arr) && $rules['rules']) {
                $validation_data_para[$field] = ($this->input->post($field) != '' ? $this->input->post($field) : $rules['default']);
                if ($field == 'email' && !$this->input->post($field))
                    continue;
                $config_rules_para[] = array('field' => $field, 'label' => $rules['label'], 'rules' => 'trim|' . $rules['rules']);
            }
        }
        //$this->set_validation_data($validation_data_para);
        $this->set_validation_rules($config_rules_para);
        
        if ($this->do_validation() == FALSE) {
            $response = array('success' => FALSE, 'feedback' => validation_errors());
        } else {
            //对输入的密码进行规则检查
            $this->load->helper('hyd_password');
            if (0 && check_password_valid($this->input->post('password')) != 3) {
                $response = array('success' => FALSE, 'feedback' => '密码无效!');
            } else {
                $field_arr = $this->_add_field_arr;
                $post_arr = array();
                $post_arr['id'] = '';
                foreach ($field_arr as $field) {
                    $post_value = $this->input->post($field);
                    $post_arr[$field] = $post_value;
                    //验证提交的值是否在有效范围内
                    if (in_array($field, $this->_save_field_valid_arr)) {
                        $field_valid_arr = $this->get_field_lists($field);
                        if (!isset($field_valid_arr['datasource'][$post_value])) {
                            $post_arr[$field] = $field_valid_arr['default'];
                        }
                    }
                }
                $post_arr['username'] = $post_arr['tel'];
                $post_arr['password'] = substr($post_arr['tel'], -4);
                $response = $this->save_user($post_arr);
            }
        }
        
        $this->admin->do_userlog(get_class(), __FUNCTION__, $this->input->post('username'), $response['feedback'], $response['success'], FALSE);
        return $response;
    }
    /**
     * 修改用户/员工
     */
    public function edit_user() {
        $field_arr = $this->_edit_field_arr;
        foreach ($this->get_field_lists() as $field => $rules) {
            if (in_array($field, $field_arr) && $rules['rules']) {
                $validation_data_para[$field] = ($this->input->post($field) != '' ? $this->input->post($field) : $rules['default']);
                if ($field == 'email' && !$this->input->post($field))
                    continue;
                $config_rules_para[] = array('field' => $field, 'label' => $rules['label'], 'rules' => 'trim|' . $rules['rules']);
            }
        }
        //$this->set_validation_data($validation_data_para);
        $this->set_validation_rules($config_rules_para);
        
        if ($this->do_validation() == FALSE) {
            $response = array('success' => FALSE, 'feedback' => validation_errors());
        } else {
            //对输入的密码进行规则检查
            $this->load->helper('hyd_password');
            if (0 && check_password_valid($this->input->post('password')) != 3) {
                $response = array('success' => FALSE, 'feedback' => '密码无效!');
            } else {
                $post_arr = array();
                foreach ($field_arr as $field) {
                    $post_value = $this->input->post($field);
                    $post_arr[$field] = $post_value;
                    //验证提交的值是否在有效范围内
                    if (in_array($field, $this->_save_field_valid_arr)) {
                        $field_valid_arr = $this->get_field_lists($field);
                        if (!isset($field_valid_arr['datasource'][$post_value])) {
                            $post_arr[$field] = $field_valid_arr['default'];
                        }
                    }
                }
                $post_arr['username'] = $post_arr['tel'];
                $response = $this->save_user($post_arr);
            }
        }
        
        $this->admin->do_userlog(get_class(), __FUNCTION__, $this->input->post('username'), $response['feedback'], $response['success'], FALSE);
        return $response;
    }
    /**
     * 添加、修改时进行的保存
     * @return $response array
     */
    private function save_user($post_arr) {
        if (0) {
            return array('success' => FALSE, 'feedback' => '没有此操作权限');
        } else {
            $res = $this->user_model->save($post_arr['id'], $post_arr);
            switch ($res) {
                case 1:
                    $response = array('success' => TRUE, 'feedback' => '保存成功！');
                    break;
                case -1:
                    $response = array('success' => FALSE, 'feedback' => lang('ms_error_email_format'));
                    break;
                case -2:
                    $response = array('success' => FALSE, 'feedback' => lang('ms_error_email_already_exists'));
                    break;
                case -3:
                    $response = array('success' => FALSE, 'feedback' => '重复注册，请核对手机号！');
                    break;
                case MODEL_RETURN_DBERROR:
                    $response = array('success' => FALSE, 'feedback' => '数据库错误！');
                    break;
            }
            return $response;
        }
    }
    
    /**
     * 修改个人密码
     */
    public function edit_password(){
        $userdata = $this->session->userdata('user_data'); //log_message('error', "---------------".print_r($userdata));
        $password = $this->input->post('password');
        $password_new = $this->input->post('password_new');
        
        if($userdata['username'] && $password){
            $result_arr = $this->user_model->verify_user($userdata['username'],$password);
        }else{
            $response = array('success' => FALSE, 'feedback' => '密码提交失败');
            return $response;
        }
        
        if($result_arr !== FALSE && $password_new){
            $result = $this->user_model->update_password($userdata['id'],$password_new);
        }else{
            $response = array('success' => FALSE, 'feedback' => '原密码错误！');
            return $response;
        }
        
        if($result === TRUE){
            $response = array('success' => TRUE, 'feedback' => '密码修改成功！');
        }else if($result === MODEL_RETURN_DBERROR){
            $response = array('success' => FALSE, 'feedback' => '数据库错误'); 
        }else{
            $response = array('success' => FALSE, 'feedback' => '密码修改失败!');
        }
        return $response;
    }
    
    /**
     * 根据id取单条记录信息
     * @return boolean
     */
    public function load_user() {
        $data = $this->user_model->get_data($this->input->post('id'));
        unset($data['password']);
        $response = array('success' => TRUE, 'data' => $data);
        return $response;
    }
    /**
     * 将某一用户置为离职
     * @return boolean
     */
    public function quit_user() {
        $response = array('success' => FALSE, 'feedback' => '离职审批失败！');
        $userdata = $this->session->userdata('user_data');        //print_r($userdata);
        $userid = $this->input->post('id');
        $createadmin = $userdata['id'];
        if($userid){
            $insert_data = array('otype'=>'Q',
                'ostatus'=>'Q3',
                'userid'=>$userid,
                'createadmin'=>$createadmin,
                'createtime'=> get_date_now()
            );
            $res = $this->user_model->update_status($this->input->post('id'), array('status'=>'Q'),$insert_data);
            switch ($res) {
                case 1:
                    $response = array('success' => TRUE, 'feedback' => '离职审批成功！');
                    break;
                case MODEL_RETURN_DBERROR:
                    $response = array('success' => FALSE, 'feedback' => '数据库错误！');
                    break;
            }
        }

        return $response;
    }
    
    public function get_department_select(){
        $this->load->model('department/department_model');
        $teamid = $this->input->get_post('teamid');
        
        if($teamid){
            $department = $this->department_model->get_lists(NULL,NULL,'teamid='.$teamid);
        }else{
            $department = $this->department_model->get_lists();
        }
        
        $department_select[] = array();
        foreach ($department as $key => $value) {
            $department_select[$key]['id'] = $value['id'];
            $department_select[$key]['text'] = $value['name'];
        }
        return $department_select;    
    }
    
    public function get_position_select(){
        $this->load->model('position/position_model');
        
        $position = $this->position_model->get_lists();
        $position_select[] = array();
        foreach ($position as $key => $value) {
            $position_select[$key]['id'] = $value['id'];
            $position_select[$key]['text'] = $value['name'];
        }
        return $position_select;
    }
    
    //文件上传
    public function do_upload($id=0,$field){
        $config['upload_path'] = './resources/images/user/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['file_name'] = 'user'.$id;
        $config['overwrite'] = TRUE;
        $config['max_size'] = '200';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';
        
        $this->load->helper(array('form'));
        $this->load->library('upload', $config);
        //$this->upload->initialize($config);   
        if ( ! $this->upload->do_upload($field)){//失败
            //echo "{\"failure\":true,feedback:\"提交信息不合法!\"}";
            //$data = array('error' => $this->upload->display_errors());
        } else { //成功
            $data = array('upload_data' => $this->upload->data());
        }
    }
    
}

/* End of file admin.php */
/* Location: ./application/controllers/admin.php */